/**
  * Created by Joshua Conero(O'Uymas) on 2016/11/15 0015.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  * 命令话窗口处理程序
  */
import org.jsoup.Jsoup
import scala.io.Source
import scala.sys.process.Process
import scala.xml.XML
import java.lang
import scala.collection.JavaConversions._
class console(conf:String){
  val helper = new Helper
  val sysdir = helper.__dir__
  var command = ""
  var param = ""
  val br = "\r\n"
  val config = "./config/config.xml"
  val xconf = XML.loadFile(config)
  // xconf\"config"\"app" - 顶部元素不用谢
  val app = xconf\"app"
  def run(args: Array[String]):Unit = {
    if(args.length>0){
      var cmd = args(0).toLowerCase
      cmd = cmd.replaceAll("-","")
      val arr = cmd.split("/")
      cmd = arr(0)
      cmd = cmd match{
        case "crawler" => "crl"
        case _ => cmd
      }
      if(args.length>1) command = args(1).replaceAll("-","").toLowerCase
      if(args.length>2) param = args(2)
      var cmdChild = ""
      if(arr.length>1) cmdChild = arr(1)
      //cmd = "env"//测试输出
      cmd match {
        case "crl" => {// 爬虫程序
          crlAction(cmdChild)
          return
        }
        case "env" =>{// 环境变量
          sysEnv()
          return
        }
        case "java" =>{// java基本环境
          javaEnv()
          return
        }
        // 帮助
        case _ => {
          about(args)
          return
        }
      }
    }
    // 测试器
    //sysEnv(true)
    //javaEnv()
    about(args)
  }
  def crlAction(ipt:String):Unit = {
    ipt match {
      case "header" =>{//获取网页的头部
        if(command == "") println(helper.sysdate()+">crl/header -地址")
        else{
          try{
            val conn = Jsoup.connect(command)
            val doc = conn.get()
            println(doc.head().toString)
          }
        }
      }
      //case (ipt == "") || (helper.is_file("")) =>{println(ipt)}
      case _ =>{
        if(command != ""){
          // 为xml文件
          if(helper.is_file(command) && helper.getFileExt(command) == "xml"){
            println("系统即将爬取-"+command+"-中解析出的数据")
            new Crawler("").ghost(command,helper.getFname(command,true))
          }
          else{
            println("-(: "+command+"不是有效的xml文件")
          }
        }
        else{
          println("crl命令下没有做任何处理-可能还输入的命令无效，请查阅相关文档")
          println("crl子命令>"+ipt)
          println("crl子命令参数>"+command)
        }
      }
    }
  }
  // 系统环境变量处理-默认参数
  def sysEnv(saveFile:Boolean = false):Unit = {
    var content = ""
    var paths = ""
    for((k,v)<-scala.sys.env){
      if(k == "Path"){
        val arr = v.split(";")
        for(pv<-arr) paths += pv+br
      }
      else content += k+" = "+v+br
    }
    val putout = "环境变量如下："+br+content+br+"系统变量如下："+br+paths+br+helper.sysdate()
    if(saveFile == true || command != ""){
      var fileName = (app\"runtime"\"@src").toString()+"env_"+helper.stamp()+(app\"runtime"\"@ext").toString()
      if(command != "") fileName = command
      var saveText = helper.sysdate()+"------------"
      saveText += br+"命令>exe -env 自定义文件名/默认"
      saveText += br+"环境变量如下：-------------"+br+content
      saveText += br+"系统变量如下：-------------"+br+paths
      saveText += br+helper.sysdate()+"------------"
      if(helper.put_content(fileName,saveText) == false){
        println(putout)
        println("无法保存文件")
      }
      else{
        try{
          fileName = fileName.replace("./",sysdir+"/")
          Process(fileName).run()
        }catch {
          case e:Exception => {
            println(fileName)
          }
        }
      }
      return
    }
    println(putout)
  }
  def javaEnv(saveFile:Boolean = false):Unit ={
    val sysInfo = System.getProperties()
    var saveText = ""
    val pathToList = (ipt:String) =>{
      var ul = ""
      val arr = ipt.split(";")
      val tb = "\r\t"
      for(v<-arr){
        ul += tb+v
      }
      println(ul)
      // 子函数中的放回会引起外部函数的中断
      //return ul
    }
    var key =""
    for(v<- sysInfo.stringPropertyNames().toArray){
      key = v.toString
      try {
        if (key.indexOf(".path") > -1){saveText += key + " => " + pathToList(System.getProperty(key)) + br}
        else{saveText += key + " => " + System.getProperty(key) + br}
      }
    }
    if(saveFile == true || command != ""){
      var fileName = (app\"runtime"\"@src").toString()+"java_"+helper.stamp()+(app\"runtime"\"@ext").toString()
      if(command != "") fileName = command
      saveText = "java信息列表如下("+helper.sysdate()+")："+br+saveText
      if(helper.put_content(fileName,saveText) == true){
        try{
          fileName = fileName.replace("./",sysdir+"/")
          Process(fileName).run()
        }catch {
          case e:Exception => {
            println(fileName)
          }
        }
      }else println(saveText+br+br+"文件保存失败")
      return
    }
    else println(saveText)
  }
  // 帮助提示
  def about(args: Array[String]):Unit = {
    var info = br+"<<<<<<<<<<<<<<<<<<<<<<<<<<<<(^_^)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+
              br+"(:= 欢迎使用-Joshua Conero Scala Start(JC2S)["+helper.sysdate()+"]"
    info += (new About).console()+
            br+ "<<<<<<<<<<<<<<<<<<<<<<<<<<<<(^_^)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+br
    println(info)
  }
}
